/* Created by wivwiv on 2018/1/2 20:00 */
import axios from 'axios'
import { Indicator } from 'mint-ui'

const baseURL = '/api/v1'

function indicator(open = true) {
  if (open) {
    Indicator.open('加载中')
  } else {
    Indicator.close()
  }
}

function httpRequest() {
  const config = {
    baseURL,
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
      Accept: 'application/json',
    },
  }

  const user = JSON.parse(sessionStorage.getItem('user')) ||
    JSON.parse(localStorage.getItem('user'))

  if (user && user.password) {
    config.headers.token = user.password
  }
  return axios.create(config)
}

function handleError(error) {
  indicator(false)
  if (error.response.status === 401) {
    window.location.href = '/login'
  } else {
    console.log('Net work error ')
  }
  return Promise.reject(error.response.data.message || '未知错误')
}

function httpGet(url, showIndicator = true) {
  if (showIndicator) {
    indicator()
  }
  return httpRequest().get(url).then((response) => {
    indicator(false)
    return response
  }).catch(handleError)
}

function httpPut(url, data, showIndicator = true) {
  if (showIndicator) {
    indicator()
  }
  const jsonData = JSON.stringify(data)
  return httpRequest().put(url, jsonData).then((response) => {
    indicator(false)
    return response
  }).catch(handleError)
}

function httpPost(url, data, showIndicator = true) {
  if (showIndicator) {
    indicator()
  }
  const jsonData = JSON.stringify(data)
  return httpRequest().post(url, jsonData).then((response) => {
    indicator(false)
    return response
  }).catch(handleError)
}

function httpDelete(url, showIndicator = true) {
  if (showIndicator) {
    indicator()
  }
  return httpRequest().delete(url).then((response) => {
    indicator(false)
    return response
  }).catch(handleError)
}

export { baseURL, httpGet, httpPut, httpPost, httpDelete }
